﻿using System.Diagnostics;

namespace NewProcessGuarder.toolFunc
{
    public class SystemTool
    {
        /// <summary>
        /// 检测进程数量
        /// </summary>
        /// <param name="sProcessesName">进程名称</param>
        /// <returns></returns>
        public static int ProcessesCount(string sProcessesName)
        {
            try
            {
                var processes = System.Diagnostics.Process.GetProcessesByName(sProcessesName);
                return processes.Length;
            }
            catch { }
            return 0;
        }

        public static void closeSelf(Process process) {
            var dul = Process.GetProcessesByName(process.ProcessName);

            if (dul.Length > 1)
            {
                foreach (var item in dul)
                {
                    if (item.Id != process.Id)
                    {
                        item.Kill();
                    }
                }
            }
        }

        /// <summary>
        /// 调用命令行执行指定的命令
        /// </summary>
        /// <param name="cmd">指定的命令</param>
        public static void RunCmd(string cmd)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            // 关闭Shell的使用
            p.StartInfo.UseShellExecute = false;
            // 重定向标准输入
            p.StartInfo.RedirectStandardInput = true;
            // 重定向标准输出
            p.StartInfo.RedirectStandardOutput = true;
            //重定向错误输出
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.WriteLine(cmd);
            p.StandardInput.WriteLine("exit");
        }

    }
}
